#!/bin/bash
# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import shutil
import json
import stat


def load_json(file_path):
    with os.fdopen(os.open(file_path, os.O_RDWR | os.O_CREAT, stat.S_IWUSR | stat.S_IRUSR), 'r', encoding='utf-8') as f:
        try:
            return json.load(f)
        except json.JSONDecodeError as e:
            print(f"Error decoding JSON: {e}")
            return None


def replace(part_name, source, dest, oh_root):
    for dst in dest:
        rk_so_path = os.path.join(oh_root, 'out', 'rk3568', 'packages', 'phone', dst)
        if not os.path.exists(source):
            continue
        if os.path.isfile(source):
            shutil.copy(source , rk_so_path)
            print(f'{part_name}:{dst} done')
        elif os.path.isdir(source):
            print(f"copy dir {source} to {rk_so_path}")
            shutil.rmtree(rk_so_path)
            shutil.copytree(source, rk_so_path)
            print(f'{part_name}:{dst} done')


def filter_item_and_replace(oh_root , part_name, so_path_list):
    system_module_file_path = os.path.join(oh_root, 'out', 'rk3568', 'packages', 'phone', 'system_module_info.json')
    if not os.path.exists(system_module_file_path):
        print(f"system_module_info.json not found: {system_module_file_path}")
        return []
    if os.path.getsize(system_module_file_path) == 0:
        print(f"File is empty: {system_module_file_path}")
        return []
    so_list = {os.path.basename(item):item for item in so_path_list}
        
    jsondata = load_json(system_module_file_path)
    for item in jsondata:
        souce_name = os.path.basename(item.get("source"))
        if item.get("part_name") == part_name and souce_name in so_list:
            dest = item.get("dest")
            source = so_list[souce_name]
            replace(part_name, source, dest, oh_root)


def record_rely_item(so_path, replace_dict, variant):
    part_path = so_path.split("innerapis/")[0].split(f"out/{variant}/src/obj/")[1]
    indep_code_dir = so_path.split(f"/out/{variant}/src")[0]
    bundle_json = os.path.join(indep_code_dir, part_path, "bundle.json")
    if os.path.exists(bundle_json):
        with open(bundle_json, "r") as f:
            data = json.load(f)
            part_name = data["component"]["name"]
            if part_name not in replace_dict:
                replace_dict[part_name] = [so_path]
            else:
                replace_dict[part_name].append(so_path)

    
def replace_rely_so(tool_dir, args):
    print("---------------------------replace rely so list -------------------------")
    replace_dict = dict()
    variant = args.variant
    obj_binarys = os.path.join(tool_dir, f"code/out/{variant}/src/obj/binarys")
    for root, _, files in os.walk(obj_binarys):
        for file in files:
            if file.endswith("so") and root.endswith("libs") and "innerapis" in root:
                so_path = os.path.join(root, file)
                record_rely_item(so_path, replace_dict, variant)
    oh_root = os.path.dirname(tool_dir)
    for part_name, so_path_list in replace_dict.items():
        filter_item_and_replace(oh_root, part_name, so_path_list)